use crate::rtmp::protocol_control_messages::errors::ProtocolControlMessageReaderError;
use crate::rtmp::user_control_messages::errors::EventMessagesError;
use bytesio::bytes_errors::BytesReadError;
use failure::{Backtrace, Fail};
use std::fmt;
use xflv::amf0::Amf0ReadError;

// 错误枚举类型
#[derive(Debug, Fail)]
pub enum MessageErrorValue {
    // 字节读取错误
    #[fail(display = "bytes read error: {}", _0)]
    BytesReadError(BytesReadError),
    // 未知读取状态
    #[fail(display = "unknow read state")]
    UnknowReadState,
    // AMF0读取错误
    #[fail(display = "amf0 read error: {}", _0)]
    Amf0ReadError(Amf0ReadError),
    // 未知消息类型
    #[fail(display = "unknown messages type")]
    UnknowMessageType,
    // 协议控制消息读取错误
    #[fail(display = "protocol control messages read error: {}", _0)]
    ProtocolControlMessageReaderError(ProtocolControlMessageReaderError),
    // 用户控制消息读取错误
    #[fail(display = "user control messages read error: {}", _0)]
    EventMessagesError(EventMessagesError),
}

// 消息错误结构体
#[derive(Debug)]
pub struct MessageError {
    pub value: MessageErrorValue,
}

impl From<MessageErrorValue> for MessageError {
    fn from(val: MessageErrorValue) -> Self {
        MessageError { value: val }
    }
}

impl From<BytesReadError> for MessageError {
    fn from(error: BytesReadError) -> Self {
        MessageError {
            value: MessageErrorValue::BytesReadError(error),
        }
    }
}

impl From<Amf0ReadError> for MessageError {
    fn from(error: Amf0ReadError) -> Self {
        MessageError {
            value: MessageErrorValue::Amf0ReadError(error),
        }
    }
}

impl From<ProtocolControlMessageReaderError> for MessageError {
    fn from(error: ProtocolControlMessageReaderError) -> Self {
        MessageError {
            value: MessageErrorValue::ProtocolControlMessageReaderError(error),
        }
    }
}

impl From<EventMessagesError> for MessageError {
    fn from(error: EventMessagesError) -> Self {
        MessageError {
            value: MessageErrorValue::EventMessagesError(error),
        }
    }
}

impl fmt::Display for MessageError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.value, f) // 使用内部值的显示格式化实现
    }
}

impl Fail for MessageError {
    fn cause(&self) -> Option<&dyn Fail> {
        self.value.cause() // 获取错误原因
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.value.backtrace() // 获取错误回溯信息
    }
}
